// pages/cart/index.js
import { showToast, requestPayment } from '../../utils/asyncWx'
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index'

Page({

  data: {
    // 收货地址
    address: {},
    // 购物车商品
    cart: [],
    // 总价格
    totalPrice: 0,
    // 总数量
    totalNum: 0
  },

  onShow: function (options) {
    const address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];

    // 筛选购物车数组 checked 为 true 的数组
    cart = cart.filter(v => v.checked)

    // 总价格、总数量
    let totalPrice = 0
    let totalNum = 0

    cart.forEach(v => {
      totalPrice += v.goods_price * v.num
      totalNum += v.num
    })

    this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    })

  },

  // 支付
  async handleOrderPay () {
    try {
      // 1 判断有没有token
      const token = wx.getStorageSync("token");
      if (!token) {
        // 2 跳转到授权页面
        wx.navigateTo({
          url: '/pages/auth/index',
        });
      } else {
        // 有 token
        // 3 创建订单 获取订单编号
        // 请求头参数 
        // const header = { Authorization: token }
        // 请求体参数
        const order_price = this.data.totalPrice
        const consignee_addr = this.data.address.all
        let goods = []
        const { cart } = this.data
        cart.forEach(v => {
          goods.push({
            goods_id: v.goods_id,
            goods_number: v.num,
            goods_price: v.goods_price
          })
        })
        const params = { order_price, consignee_addr, goods }
        // 发起创建订单请求
        const { order_number } = request({ url: "/my/orders/create", data: params, method: "post" })

        // 4 发起预支付请求
        const { pay } = request({ url: "/my/orders/req_unifiedorder", data: { order_number }, method: "post" })

        // 5 发起微信支付
        await requestPayment(pay)

        // 6 查询后台 订单状态
        request({ url: "/my/orders/chkOrder", data: { order_number }, method: "post" })

        // 7 手动删除缓存中已经支付完的商品
        const newCart = wx.getStorageSync("cart");
        newCart.filter(v => !v.checked)
        wx.setStorageSync("cart", newCart);

        // 8 支付成功 跳转到订单页面
        wx.navigateTo({
          url: '/pages/order/index',
        });

        await showToast({ title: "支付成功!" })
      }
    } catch (error) {
      await showToast({ title: "支付失败!" })
      console.log(error)
    }
  }

})